<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>车厢管理 - 铁路管理系统</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="/admin/css/styles.css">
    <style>
        #app2 {
            display: flex;
            min-height: 100vh;
            width: 100%; /* 添加此行使容器宽度填满页面 */
        }
    </style>
</head>
<body>
<div id="app2">
    <!-- 主内容区 -->
    <div class="main-content">

        <!-- 页面内容区域 -->
        <div id="page-content" style="padding: 0 20px;">
            <!-- 搜索和添加区域 -->
            <div class="card mb-4">
                <div class="card-header">
                    <h3 class="card-title">车厢查询</h3>
                </div>
                <div class="card-body">
                    <form class="form-row" @submit.prevent="search">
                        <div class="form-group col-3">
                            <label for="trainNumber">车辆号</label>
                            <input type="text" v-model="searchForm.trainNumber" class="form-control" id="trainNumber"
                                   placeholder="请输入车次号">
                        </div>
                        <div class="form-group col-3">
                            <label for="carriageNumber">车厢编号</label>
                            <input type="number" v-model="searchForm.carriageNumber" class="form-control"
                                   id="carriageNumber"
                                   placeholder="请输入车厢编号">
                        </div>
                        <div class="form-group col-3">
                            <label for="carriageType">车厢类型</label>
                            <select v-model="searchForm.carriageType" class="form-control" id="carriageType">
                                <option value="">全部</option>
                                <option value="1">一等座</option>
                                <option value="2">二等座</option>
                            </select>
                        </div>
                        <div class="form-group col-3" style="display: flex; align-items: flex-end;">
                            <button type="submit" class="btn btn-primary" style="margin-right: 10px;">
                                <i class="fas fa-search"></i> 搜索
                            </button>
                            <button type="button" class="btn btn-success" @click="openModal('添加车厢')">
                                <i class="fas fa-plus"></i> 添加车厢
                            </button>
                        </div>
                    </form>
                </div>
            </div>

            <!-- 数据表格区域 -->
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">车厢列表</h3>
                </div>
                <div class="card-body">
                    <div class="table-container">
                        <table class="table">
                            <thead>
                            <tr>
                                <th>车厢ID</th>
                                <th>车辆号</th>
                                <th>车厢编号</th>
                                <th>车厢类型</th>
                                <th>座位总数</th>
                                <th>无座票数量</th>
                                <th>创建时间</th>
                                <th>操作</th>
                            </tr>
                            </thead>
                            <tbody>
                            <tr v-for="item in paginatedData" :key="item.carriageId">
                                <td>{{ item.carriageId }}</td>
                                <td>{{ item.trainNumber || '-' }}</td>
                                <td>{{ item.carriageNumber || '-' }}</td>
                                <td>{{ item.carriageType === 1 ? '一等座' : item.carriageType === 2 ? '二等座' : '-'
                                    }}
                                </td>
                                <td>{{ item.seatCount || '-' }}</td>
                                <td>{{ item.noSeatCount || '-' }}</td>
                                <td>{{ item.createTime || '-' }}</td>
                                <td>
                                    <button class="btn btn-primary btn-sm" @click="handleEdit(item)">
                                        <i class="fas fa-edit"></i> 编辑
                                    </button>
                                    <button class="btn btn-danger btn-sm" @click="handleDelete(item.carriageId)">
                                        <i class="fas fa-trash"></i> 删除
                                    </button>
                                </td>
                            </tr>
                            <tr v-if="paginatedData.length === 0">
                                <td colspan="8" style="text-align: center;">暂无数据</td>
                            </tr>
                            </tbody>
                        </table>
                    </div>
                    <!-- 分页区域 -->
                    <div class="pagination"
                         style="margin-top: 20px; display: flex; justify-content: center; align-items: center;">
                        <button class="btn btn-sm" :disabled="currentPage === 1" @click="prevPage">&laquo;</button>

                        <span class="page-info" style="margin: 0 10px;">
                            第 {{ startIndex + 1 }}-{{ endIndex }} 条，共 {{ totalItems }} 条
                        </span>

                        <div class="page-numbers" style="display: flex; margin: 0 10px;">
                            <button v-for="page in pages" :key="page"
                                    class="btn btn-sm"
                                    :class="{ 'btn-primary': page === currentPage }"
                                    @click="goToPage(page)">
                                {{ page }}
                            </button>
                        </div>

                        <button class="btn btn-sm" :disabled="currentPage === totalPages" @click="nextPage">&raquo;
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 编辑模态框 -->
    <div v-if="isModalVisible" class="modal"
         style="position: fixed; z-index: 1000; left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgba(0,0,0,0.4);">
        <div class="modal-content"
             style="background-color: #fefefe; margin: 15% auto; padding: 20px; border: 1px solid #888; width: 80%; max-width: 600px; border-radius: 8px;">
            <div class="modal-header" style="padding: 10px 0; border-bottom: 1px solid #ddd; margin-bottom: 20px;">
                <h3>{{ currentModalTitle }}</h3>
                <span class="close"
                      style="color: #aaa; float: right; font-size: 28px; font-weight: bold; cursor: pointer;"
                      @click="closeModal">&times;</span>
            </div>
            <form @submit.prevent="saveData">
                <input type="hidden" v-model="formData.carriageId">
                <div class="form-row">
                    <div class="form-group col-6">
                        <label for="editTrainNumber">车辆号 <span style="color: red;">*</span></label>
                        <!-- 将输入框改为下拉框 -->
                        <select v-model="formData.trainNumber" class="form-control" id="editTrainNumber" required>
                            <option value="">请选择车辆号</option>
                            <option v-for="train in trainList" :key="train.trainNumber" :value="train.trainNumber">
                                {{ train.trainNumber }}
                            </option>
                        </select>
                    </div>
                    <div class="form-group col-6">
                        <label for="editCarriageNumber">车厢编号 <span style="color: red;">*</span></label>
                        <input type="number" v-model="formData.carriageNumber" class="form-control"
                               id="editCarriageNumber" min="1" required>
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group col-6">
                        <label for="editCarriageType">车厢类型 <span style="color: red;">*</span></label>
                        <select v-model="formData.carriageType" class="form-control" id="editCarriageType" required>
                            <option value="1">一等座</option>
                            <option value="2">二等座</option>
                        </select>
                    </div>
                    <div class="form-group col-6">
                        <label for="editSeatCount">座位总数 <span style="color: red;">*</span></label>
                        <input type="number" v-model="formData.seatCount" class="form-control" id="editSeatCount"
                               min="1" required>
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group col-6">
                        <label for="editNoSeatCount">无座票数量</label>
                        <input type="number" v-model="formData.noSeatCount" class="form-control" id="editNoSeatCount"
                               min="0" value="0">
                    </div>
                </div>
                <div class="form-group" style="margin-top: 20px;">
                    <button type="submit" class="btn btn-primary" style="margin-right: 10px;">保存</button>
                    <button type="button" class="btn btn-secondary" @click="closeModal">取消</button>
                </div>
            </form>
        </div>
    </div>
</div>
<script src="/admin/js/auth.js"></script>
<script src="/admin/js/jquery-3.6.0.js"></script>
<script src="/admin/js/vue.js"></script>
<script src="/admin/js/load-navbar.js"></script>
<script src="/admin/js/user-info.js"></script>
<script src="/admin/js/script.js"></script>
<script src="/admin/js/axios.js"></script>
<script src="/admin/js/config.js"></script>
<script>
    new Vue({
        el: '#app2',
        data: {
            searchForm: {
                trainNumber: '',
                carriageNumber: '',
                carriageType: ''
            },
            tableData: [],
            formData: {},
            isModalVisible: false,
            currentModalTitle: '',
            userName: '',
            trainList: [], // 添加车辆列表数据

            // 分页相关数据
            currentPage: 1,
            pageSize: 8,
            totalItems: 0,
            // 控制是否使用前端分页
            useFrontendPagination: false
        },
        computed: {
            // 计算总页数
            totalPages() {
                return Math.ceil(this.totalItems / this.pageSize);
            },
            // 当前页显示的数据
            paginatedData() {
                return this.tableData;
            },
            // 显示的页码范围
            pages() {
                const pages = [];
                const maxVisiblePages = 5; // 最多显示5个页码
                let startPage = Math.max(1, this.currentPage - Math.floor(maxVisiblePages / 2));
                let endPage = Math.min(this.totalPages, startPage + maxVisiblePages - 1);
                if (endPage - startPage < maxVisiblePages - 1) {
                    startPage = Math.max(1, endPage - maxVisiblePages + 1);
                }
                for (let i = startPage; i <= endPage; i++) {
                    pages.push(i);
                }
                return pages;
            },

            // 当前页起始索引
            startIndex() {
                return (this.currentPage - 1) * this.pageSize;
            },

            // 当前页结束索引
            endIndex() {
                const end = this.startIndex + this.pageSize;
                return Math.min(end, this.totalItems);
            },

        },
        methods: {
            search() {
                this.currentPage = 1; // 搜索时重置到第一页
                this.loadData();
                console.log('搜索条件:', this.searchForm);
            },
            openModal(title) {
                this.resetForm();
                this.currentModalTitle = title;
                this.loadTrainList(); // 打开模态框时加载车辆列表
                this.isModalVisible = true;
            },
            closeModal() {
                this.isModalVisible = false;
                this.formData = {};
            },
            resetForm() {
                this.formData = {
                    carriageId: '',
                    trainNumber: '',
                    carriageNumber: '',
                    carriageType: '1',
                    seatCount: '',
                    noSeatCount: 0
                };
            },
            handleEdit(item) {
                this.formData = {...item};
                this.currentModalTitle = '编辑车厢信息';
                this.loadTrainList(); // 打开模态框时加载车辆列表
                this.isModalVisible = true;
            },
            handleDelete(id) {
                if (confirm(`确定要删除ID为 ${id} 的车厢信息吗？`)) {
                    // 调用后端API删除数据
                    axios.delete(`/admin/train_carriage_manage/delete/${id}`)
                        .then(resp => {
                            if (resp.data.code === 200) {
                                alert('删除成功');
                                this.loadData(); // 重新加载数据
                            } else {
                                alert('删除失败: ' + resp.data.message);
                            }
                        })
                        .catch(error => {
                            console.error('删除请求失败:', error);
                            alert('删除失败，请重试');
                        });
                }
            },
            saveData() {
                if (!this.formData.trainNumber || !this.formData.carriageNumber || !this.formData.seatCount) {
                    alert('请填写必填字段');
                    return;
                }
                const url = this.formData.carriageId ? '/admin/train_carriage_manage/update' : '/admin/train_carriage_manage/add';
                axios.post(url, this.formData)
                    .then(resp => {
                        if (resp.data.code === 200) {
                            alert(this.formData.carriageId ? '编辑成功' : '添加成功');
                            this.closeModal();
                            this.loadData(); // 重新加载数据
                        } else {
                            alert(this.formData.carriageId ? '编辑失败: ' : '添加失败: ' + resp.data.message);
                        }
                    })
                    .catch(error => {
                        console.error('保存请求失败:', error);
                        alert('操作失败，请重试');
                    });
            },
            //加载车辆号，下拉框选择
            loadTrainList() {
                axios.post("/admin/train_carriage_manage/loadTrainList")
                    .then(resp => {
                        if (resp.data.code === 200) {
                            //将车辆列表赋值给下拉框回显
                            this.trainList = resp.data.data || [];
                        } else {
                            alert('加载车辆列表失败: ' + resp.data.message);
                            this.trainList = [];
                        }
                    })
                    .catch(error => {
                        console.error('加载车辆列表请求失败:', error);
                        alert('加载车辆列表失败，请重试');
                        this.trainList = [];
                    });
            },
            // 分页方法
            prevPage() {
                if (this.currentPage > 1) {
                    this.currentPage--;
                    this.loadData();
                }
            },

            nextPage() {
                if (this.currentPage < this.totalPages) {
                    this.currentPage++;
                    this.loadData();
                }
            },

            goToPage(page) {
                this.currentPage = page;
                this.loadData();
            },

            loadData() {
                axios.get("/admin/train_carriage_manage/getList", {
                    params: {
                        page: this.currentPage,
                        pageSize: this.pageSize,
                        trainNumber: this.searchForm.trainNumber || null,
                        carriageNumber: this.searchForm.carriageNumber || null,
                        carriageType: this.searchForm.carriageType || null
                    }
                })
                    .then(resp => {
                        console.log('请求参数:', {currentPage: this.currentPage, pageSize: this.pageSize});
                        console.log('响应数据:', resp.data.data.list);

                        // 根据实际后端返回数据结构调整
                        if (resp.data.code === 200) {
                            // 确保数据格式正确
                            this.tableData = resp.data.data.list || [];
                            this.totalItems = resp.data.data.total || 0;
                        } else {
                            alert("加载数据失败: " + resp.message);
                            this.tableData = [];
                            this.totalItems = 0;
                        }
                    })
                    .catch(error => {
                        console.error("请求错误:", error);
                        alert("加载数据失败，请检查网络连接");
                        this.tableData = [];
                        this.totalItems = 0;
                    });
            }
        },
        mounted() {
            this.loadData();
        },
        created() {
            // 从localStorage获取用户名
            this.userName = localStorage.getItem('savedAdminName') || '用户';

            // 检查是否已登录（是否有token）
            const token = localStorage.getItem('saToken');
            if (!token) {
                // 如果没有token，跳转回登录页
                window.location.href = "/admin/login.html";
            }
        }
    });
</script>
</body>
</html>
